﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace AVIS.OutBound.WizardAgent.Helpers
{
    /// <summary>
    /// 解析XML的帮助类
    /// </summary>
    /// <remarks>
    /// 参考网址
    ///     Using LINQ to XML to Parse a SOAP message
    ///     http://stackoverflow.com/questions/4329825/using-linq-to-xml-to-parse-a-soap-message
    /// </remarks>
    public sealed class XmlHelpler
    {
        /// <summary>
        /// 查找XML节点
        /// </summary>
        /// <param name="parentElement"></param>
        /// <param name="xElementName"></param>
        /// <param name="xNamespace"></param>
        /// <returns></returns>
        public static XElement FindXElement(XElement parentElement, string xElementName, string xNamespace = null)
        {
            XNamespace ns = !string.IsNullOrWhiteSpace(xNamespace) ? XNamespace.Get(xNamespace) : null;
            return FindXElement(parentElement, xElementName, ns);
        }

        /// <summary>
        /// 查找XML节点
        /// </summary>
        /// <param name="parentElement"></param>
        /// <param name="xElementName"></param>
        /// <param name="xNamespace"></param>
        /// <returns></returns>
        public static XElement FindXElement(XElement parentElement, string xElementName, XNamespace xNamespace = null)
        {
            if (parentElement == null)
            {
                return null;
            }

            // 查找直接子节点
            var xName = xNamespace != null ? xNamespace + xElementName : xElementName;
            var element = parentElement.Element(xName);
            if (element != null)
            {
                return element;
            }

            // 查找返回包含xName的子代元素集合
            var xElements = parentElement.Descendants(xName);
            if (xElements.Count() >= 1)
            {
                return xElements.ElementAt(0);
            }

            return null;
        }

        /// <summary>
        /// 解析XML节点的值（如果有Attribute，则取Attribute对应的值，否则就是节点的Value）
        /// </summary>
        /// <param name="element"></param>
        /// <param name="xAttributeName"></param>
        /// <returns></returns>
        public static string ParseValue(XElement element, string xAttributeName = "")
        {
            if (element == null)
            {
                return "";
            }

            string result = string.Empty;
            if (string.IsNullOrEmpty(xAttributeName))
            {
                result = element.Value;
            }
            else
            {
                var attribute = element.Attribute(xAttributeName);
                if (attribute != null)
                {
                    result = attribute.Value;
                }
                else
                {
                    result = "";
                }
            }

            return result;
        }
    }
}
